package com.example.shiro.common.response;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther 严旭平
 * @date 2020/4/817:19
 * @Description
 */
@Data
@ApiModel(value = "全局统一返回结果")
public class R implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String msg;

    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<>();

    private R() {
    }

    /**
     * 操作成功响应
     *
     * @return
     */
    public static R ok() {
        R r = new R();
        r.setSuccess(CommonCode.SUCCESS.getSuccess());
        r.setCode(CommonCode.SUCCESS.getCode());
        r.setMsg(CommonCode.SUCCESS.getMsg());
        return r;
    }

    /**
     * 未知错误
     *
     * @return
     */
    public static R error() {
        R r = new R();
        r.setSuccess(CommonCode.UNKNOWN_REASON.getSuccess());
        r.setCode(CommonCode.UNKNOWN_REASON.getCode());
        r.setMsg(CommonCode.UNKNOWN_REASON.getMsg());
        return r;
    }

    /**
     * 通过枚举设置响应码
     *
     * @param commonCode
     * @return
     */
    public static R setResult(CommonCode commonCode) {
        R r = new R();
        r.setSuccess(commonCode.getSuccess());
        r.setCode(commonCode.getCode());
        r.setMsg(commonCode.getMsg());
        return r;
    }

    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    public R msg(String message) {
        this.setMsg(message);
        return this;
    }

    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map) {
        this.setData(map);
        return this;
    }
}

